package cn.com.cetccst.mqtt;

import android.content.Context;
import android.os.Build;

import androidx.annotation.NonNull;

import org.eclipse.paho.client.mqttv3.MqttException;
import org.slf4j.Logger;

import cn.com.cetccst.mqtt.log.MqttLogger;
import cn.com.cetccst.tools.device.Device;

public class MqttManager {

    public enum STATE {
        DISCONNECTED, CONNECTING, RECONNECTING, CONNECTED
    }

    private MqttManager() {
    }

    public static void setLogger(Logger logger) {
        MqttLogger.setLogger(logger);
    }

    public interface MessageCallback {

        void onMessageArrived(String message);
    }
    public interface StateCallback {

        void onStateChanged(MqttManager.STATE state);
    }

    public static class Builder {
        private final String server;
        private String clientId;
        private StateCallback stateCallback;
        public Builder(@NonNull Context context, @NonNull String server, StateCallback stateCallback) {
            this.server = server;
            clientId = getClientID(context);
            this.stateCallback = stateCallback;
        }

        public Builder setClientId(String clientId) {
            this.clientId = clientId;
            return this;
        }

        public ISSMqttClient build() {
            try {
                MqttClientImp mqttClientImp = new MqttClientImp(clientId, server, stateCallback);
                return mqttClientImp;
            } catch (MqttException e) {
                MqttLogger.error("Mqtt init error", e);
                throw new RuntimeException(e);
            }
        }
    }

    private static String getClientID(Context context) {
        return Build.MANUFACTURER + Device.getDeviceId(context);
    }

    private static boolean isValidDeviceID(String deviceId) {
        return !(deviceId == null || deviceId.isEmpty() || allSameChar(deviceId) || Build.UNKNOWN.equals(deviceId));
    }

    private static boolean allSameChar(String s) {
        char c0 = s.charAt(0);
        int i, len;
        for (i = 1, len = s.length(); i < len && s.charAt(i) == c0; i++) {
        }
        return i == len;
    }
}
